from django.http import HttpResponse, JsonResponse, FileResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.views.generic import ListView
from django.views.generic.base import TemplateResponseMixin, TemplateView

from drf21 import settings
from drf21_04.models import student
from django.core.paginator import Paginator
def page(request):
    p_num = request.GET.get('p_num',1)
    print(p_num)
    # 查询所有数据
    students = student.objects.all()

    # 创建分页器对象
    paginator = Paginator(students,3)#3代表每页展示的数据为3条
    students_data = paginator.page(p_num)#p_num当前的页数
    print(page)
    data = []
    for i in students_data:
        datas = {
            'name':i.name,
            'sex':i.sex,
            'age':i.age
        }
        data.append(datas)
    return  JsonResponse({'data':data},    json_dumps_params={'ensure_ascii':False})

def Upload(request):
    if request.method == 'POST':
        file = request.FILES.get('file')


        path = settings.upload_path+file.name


        try:
            with open(path,'wb') as f:
                for i in file.chunks():
                    print(i)
                    f.write(i)
        except:
            return HttpResponse('上传失败')
        return HttpResponse('上传成功')



def Download(request):
    path = settings.download_path+'django课件.zip'
    files = open(path,'rb')
    response = FileResponse(files)
    response['Content-Type'] = 'application/octet-stream'
    response['Comntent-Disposition'] = 'attachment;filename={}'.format(path)
    return response

def Exhibition(request):
    file = 'django课件.zip'
    return render(request,'drf21_08/demo.html',{'file':file})


class Hello(View):
    def get(self,request):
        return HttpResponse('get方法')
    def post(self,request):
        return HttpResponse('post方法')
    def put(self,request):
        return HttpResponse('put方法')

from django.views.generic.base import TemplateView


class HomePageView(ListView):

    template_name = "drf21_08_list"               #视图返回的页面

    # def get_context_data(self, **kwargs):     #向上下文变量中添加额外的数据

